import CryptoJS from "crypto-js";

export const formatZero = (num: number, len = 2) => {
  const str = "" + num;
  if (str.length < len) {
    return (new Array(len).join("0") + str).substring(str.length - 1);
  }
  return str;
};
export const gbUrl = (assetUrl: string) => {
  return `url('${assetUrl}')`;
};
/**
 * 将对象加密为字符串
 * @param obj 加密对象
 */
export const objEncodeToStr = (obj: any) => {
  const strObj = JSON.stringify(obj);
  const words = CryptoJS.enc.Utf8.parse(strObj);
  const base64 = CryptoJS.enc.Base64.stringify(words);
  return base64;
};
/**
 * 将字符串解密为对象
 * @param base64Str 加密后字符串
 */
export const strDecodeToObj = (base64Str: string) => {
  const words = CryptoJS.enc.Base64.parse(base64Str);
  const textString = CryptoJS.enc.Utf8.stringify(words);
  const obj = JSON.parse(textString);
  return obj;
};

// 数字精度
export const keepDecimal = (num: number, keep: number): number => {
  return +num.toFixed(keep);
};

//  生成区间内的随机数
export const random = (min: number, max: number) => {
  if (min > max) {
    [min, max] = [max, min];
  }
  return Math.floor(Math.random() * (max - min + 1) + min);
};
// 从数组中随机返回一个
export const getRandomOne = (arr: any[]) => {
  if (arr.length) {
    const newArr = JSON.parse(JSON.stringify(arr));
    return newArr[Math.floor(Math.random() * newArr.length)];
  }
  return undefined;
};

// 对象属性累加
export const accumulateObject = (...objList: any[]) => {
  const res = objList.reduce((total, obj) => {
    if (total) {
      const current = JSON.parse(JSON.stringify(total));
      Object.keys(current).forEach(key => {
        if (
          current[key].__proto__.constructor === Number &&
          obj[key].__proto__.constructor === Number
        ) {
          current[key] += obj[key];
        }
      });
      return current;
    }
    return JSON.parse(JSON.stringify(obj));
  }, null);
  return res;
};

// 成长曲线算法
export const growthCurve = (level: number, growth: number) => {
  return (Math.pow(growth, 2) * Math.pow(level + 1, 2)) / 100 + 1;
};
